package com.yfree.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;

/**
 * 自定义可以滑动的RelativeLayout, 类似于IOS的滑动删除页面效果，
 * 当我们要使用此功能的时候，需要将配置文件中加入“android:theme="@style/AppThemeTrans"
 * 并使用setContentView(layoutId,scrollAble);
 *
 * @author yangzhe
 */
public class YSildingFinishLayout extends RelativeLayout {
    /**
     * SildingFinishLayout布局的父布局
     */
    private ViewGroup mParentView;
    /**
     * 处理滑动逻辑的View
     */
    private View touchView;
    /**
     * 滑动的最小距离
     */
    private int mTouchSlop;
    /**
     * 按下点的X坐标
     */
    private int downX;
    /**
     * 按下点的Y坐标
     */
    private int downY;
    /**
     * 临时存储X坐标
     */
    private int tempX;
    /**
     * 滑动类
     */
    private Scroller mScroller;
    /**
     * SildingFinishLayout的宽度
     */
    private int viewWidth;
    /**
     * 记录是否正在滑动
     */
    private boolean isSilding;

    private OnSildingFinishListener onSildingFinishListener;
    private boolean isFinish;

    private int finishDistance;
    private boolean isIntercept = false;//是否拦截

    private int viewPagerPosition = 0;


    public YSildingFinishLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public YSildingFinishLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mScroller = new Scroller(context);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
// 获取SildingFinishLayout所在布局的父布局
            mParentView = (ViewGroup) this.getParent();
// mParentView = this;
            viewWidth = this.getWidth();
        }
    }

    /**
     * 设置OnSildingFinishListener, 在onSildingFinish()方法中finish Activity
     *
     * @param onSildingFinishListener
     */
    public void setOnSildingFinishListener(
            OnSildingFinishListener onSildingFinishListener) {
        this.onSildingFinishListener = onSildingFinishListener;
    }

    /**
     * 设置Touch的View
     *
     * @param touchView
     */
    public void setTouchView(View touchView) {
        this.touchView = touchView;
    }

    public View getTouchView() {
        return touchView;
    }

    /**
     * 设置滑动关闭距离
     *
     * @param finishDistance
     */
    public void setFinishDistance(int finishDistance) {
        this.finishDistance = finishDistance;
    }

    /**
     * 滚动出界面
     */
    public void scrollRight() {
        isFinish = true;
        final int delta = (viewWidth + mParentView.getScrollX());
        // 调用startScroll方法来设置一些滚动的参数，我们在computeScroll()方法中调用scrollTo来滚动item
        mScroller.startScroll(mParentView.getScrollX(), 0, -delta + 1, 0, Math.abs(delta));
        invalidate();
    }

    /**
     * 滚动到起始位置
     */
    public void scrollOrigin() {
        isFinish = false;
        int delta = mParentView.getScrollX();
        mScroller.startScroll(mParentView.getScrollX(), 0, -delta, 0,
                Math.abs(delta));
        invalidate();
    }

    /**
     * touch的View是否是AbsListView， 例如ListView, GridView等其子类
     *
     * @return
     */
    private boolean isTouchOnAbsListView() {
        return touchView instanceof AbsListView;
    }

    /**
     * touch的view是否是ScrollView或者其子类
     *
     * @return
     */
    private boolean isTouchOnScrollView() {
        return touchView instanceof ScrollView;
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = tempX = (int) event.getRawX();
                downY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) event.getRawX();
                int deltaX = tempX - moveX;
                tempX = moveX;
                if (Math.abs(moveX - downX) > mTouchSlop && Math.abs((int) event.getRawY() - downY) < mTouchSlop) {
                    isSilding = true;

// 若touchView是AbsListView，
// 则当手指滑动，取消item的点击事件，不然我们滑动也伴随着item点击事件的发生
                    if (isTouchOnAbsListView()) {
                        MotionEvent cancelEvent = MotionEvent.obtain(event);
                        cancelEvent
                                .setAction(MotionEvent.ACTION_CANCEL
                                        | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                        touchView.onTouchEvent(cancelEvent);
                    }

                }
                if (moveX - downX >= 0 && isSilding) {
// mParentView.scrollBy(deltaX, 0);
                    mParentView.scrollTo(downX - moveX, 0);

// 屏蔽在滑动过程中ListView ScrollView等自己的滑动事件
                    if (isTouchOnScrollView() || isTouchOnAbsListView()) {
                        return true;
                    }
                }
                if (!isSilding && isIntercept) {
                    if (touchView != null && event != null) {
                        touchView.onTouchEvent(event);
                    }
                }
                //preContentView.setTranslationX();
                break;
            case MotionEvent.ACTION_UP:
                isSilding = false;
                if (mParentView.getScrollX() <= -viewWidth / 4) {
// if (mParentView.getScrollX() <= -viewWidth / 2) {
                    //if (mParentView.getScrollX() <= -finishDistance) {
                    isFinish = true;
                    scrollRight();
                } else {
                    scrollOrigin();
                    isFinish = false;
                }
                break;
        }

// 假如touch的view是AbsListView或者ScrollView 我们处理完上面自己的逻辑之后
// 再交给AbsListView, ScrollView自己处理其自己的逻辑
// if (isTouchOnScrollView() || isTouchOnAbsListView()) {
// return touchView.onTouchEvent(event);
// }

// 其他的情况直接返回true
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) ev.getRawX();
                downY = (int) ev.getRawY();
                isIntercept = false;
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getRawX();
                if (Math.abs(moveX - downX) > mTouchSlop
                        && Math.abs((int) ev.getRawY() - downY) < mTouchSlop) {
                    isIntercept = true;
                    if (downX < ev.getRawX() + 10 && viewPagerPosition == 0) {
//BananasLoger.debug("右滑，downX="+downX+",ev.getRawX()="+ev.getRawX());
                        return true;
                    } else {
//BananasLoger.debug("左滑，downX="+downX+",ev.getRawX()="+ev.getRawX());
                        return false;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public void computeScroll() {
// 调用startScroll的时候scroller.computeScrollOffset()返回true，
        if (mScroller.computeScrollOffset()) {
            mParentView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();

            if (mScroller.isFinished()) {

                if (onSildingFinishListener != null && isFinish) {
                    onSildingFinishListener.onSildingFinish();
                }
            }
        }
    }


    public interface OnSildingFinishListener {
        void onSildingFinish();
    }

    public void setViewPagerPosition(int viewPagerPosition) {
        this.viewPagerPosition = viewPagerPosition;
    }
}

//public class YSildingFinishLayout extends RelativeLayout {
//
//
//    private ViewGroup mParentView;
//
//    /**
//     * 滑动的最小距离
//     */
//    private int mTouchSlop;
//
//    /**
//     * 按下点的X坐标
//     */
//
//    private int downX;
//
//    /**
//     * 按下点的Y坐标
//     */
//
//    private int downY;
//
//    /**
//     * 临时存储X坐标
//     */
//
//    private int tempX;
//
//    /**
//     * 滑动类
//     */
//
//    private Scroller mScroller;
//
//    /**
//     * SildingFinishLayout的宽度
//     */
//
//    private int viewWidth;
//
//    private boolean isSilding;
//
//    private OnSildingFinishListener onSildingFinishListener;
//    private boolean isFinish;
//
//    public YSildingFinishLayout(Context context, AttributeSet attrs) {
//        this(context, attrs, 0);
//    }
//
//    public YSildingFinishLayout(Context context, AttributeSet attrs, int defStyle) {
//        super(context, attrs, defStyle);
//        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
//        mScroller = new Scroller(context);
//    }
//
//    @Override
//    public boolean onInterceptTouchEvent(MotionEvent ev) {
//        switch (ev.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                downX = tempX = (int) ev.getRawX();
//                downY = (int) ev.getRawY();
//                break;
//            case MotionEvent.ACTION_MOVE:
//                int moveX = (int) ev.getRawX();
//                // 满足此条件屏蔽SildingFinishLayout里面子类的touch事件
//                if (Math.abs(moveX - downX) > mTouchSlop
//                        && Math.abs((int) ev.getRawY() - downY) < mTouchSlop) {
//                    return true;
//                }
//                break;
//        }
//        return super.onInterceptTouchEvent(ev);
//    }
//
//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_MOVE:
//                int moveX = (int) event.getRawX();
//                int deltaX = tempX - moveX;
//                tempX = moveX;
//                if (Math.abs(moveX - downX) > mTouchSlop
//                        && Math.abs((int) event.getRawY() - downY) < mTouchSlop) {
//                    isSilding = true;
//                }
//                if (moveX - downX >= 0 && isSilding) {
//                    mParentView.scrollBy(deltaX, 0);
//                }
//                break;
//            case MotionEvent.ACTION_UP:
//                isSilding = false;
//                if (mParentView.getScrollX() <= -viewWidth / 4) {
//                    isFinish = true;
//                    scrollRight();
//                } else {
//                    scrollOrigin();
//                    isFinish = false;
//                }
//                break;
//        }
//        return true;
//    }
//
//    @Override
//    protected void onLayout(boolean changed, int l, int t, int r, int b) {
//        super.onLayout(changed, l, t, r, b);
//        if (changed) {
//            // 获取SildingFinishLayout所在布局的父布局
//            mParentView = (ViewGroup) this.getParent();
//            viewWidth = this.getWidth();
//        }
//    }
//
//
//    /**
//     * 设置OnSildingFinishListener, 在onSildingFinish()方法中finish Activity
//     *
//     * @param onSildingFinishListener
//     */
//
//    public void setOnSildingFinishListener(
//            OnSildingFinishListener onSildingFinishListener) {
//        this.onSildingFinishListener = onSildingFinishListener;
//    }
//
//
//    /**
//     * 滚动出界面
//     */
//
//    private void scrollRight() {
//        final int delta = (viewWidth + mParentView.getScrollX());
//        // 调用startScroll方法来设置一些滚动的参数，我们在computeScroll()方法中调用scrollTo来滚动item
//        mScroller.startScroll(mParentView.getScrollX(), 0, -delta + 1, 0,
//                Math.abs(delta));
//        postInvalidate();
//    }
//
//
//    /**
//     * 滚动到起始位置
//     */
//
//    private void scrollOrigin() {
//        int delta = mParentView.getScrollX();
//        mScroller.startScroll(mParentView.getScrollX(), 0, -delta, 0,
//                Math.abs(delta));
//        postInvalidate();
//    }
//
//    @Override
//    public void computeScroll() {
//        // 调用startScroll的时候scroller.computeScrollOffset()返回true，
//        if (mScroller.computeScrollOffset()) {
//            mParentView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
//            postInvalidate();
//            if (mScroller.isFinished() && isFinish) {
//                if (onSildingFinishListener != null) {
//                    onSildingFinishListener.onSildingFinish();
//                } else {
//                    // 没有设置OnSildingFinishListener，让其滚动到其实位置
//                    scrollOrigin();
//                    isFinish = false;
//                }
//            }
//        }
//    }
//
//    public interface OnSildingFinishListener {
//        void onSildingFinish();
//    }
//}
